package com.yangmf.auto_message_handle.service.serviceimpl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yangmf.auto_message_handle.content.BaseContext;
import com.yangmf.auto_message_handle.pojo.dto.CharacterDTO;
import com.yangmf.auto_message_handle.pojo.dto.UserDTO;
import com.yangmf.auto_message_handle.pojo.dto.UserLoginDTO;
import com.yangmf.auto_message_handle.pojo.entity.Student;
import com.yangmf.auto_message_handle.pojo.entity.User;
import com.yangmf.auto_message_handle.mapper.UserMapper;
import com.yangmf.auto_message_handle.pojo.vo.CharacterVO;
import com.yangmf.auto_message_handle.pojo.vo.UserVO;
import com.yangmf.auto_message_handle.properties.WeChatProperties;
import com.yangmf.auto_message_handle.service.UserService;
import com.yangmf.auto_message_handle.utils.HttpClientUtil;
import jakarta.validation.constraints.Max;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private WeChatProperties weChatProperties;


    @Autowired
    private UserMapper userMapper;
    public static final String WX_LOGIN="https://api.weixin.qq.com/sns/jscode2session";

    @Override
   public User wxLogin(UserLoginDTO userLoginDTO)
    {
        //向wx客户端发送消息获取信息
        String openid = getOpenID(userLoginDTO.getCode());
        log.info("openid:{}",openid);


        if(openid==null)
        {

            throw new RuntimeException("登录错误");
        }
        //判断是不是新用户

        User user = userMapper.selectUserByOpenid(openid);


        //如果是新用户，插入数据库
        if(user==null)
        {
           user= User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                   .name("用户"+ UUID.randomUUID().toString())
                   .avatar("https://java-auto-handle-message.oss-cn-beijing.aliyuncs.com/0229ce09b39fbb755a4a747a993e2d2a.jpg")
                   .IsComplete(0L)
                    .build();

            userMapper.insert(user);
        }





        //返回用户信息
        return user;

    };

    @Override
    public void updateAvatar(String url){
        log.info("开始更新用户头像");
        Long id = BaseContext.getCurrentId();

        userMapper.updateAvatar(url,id);
    };


    @Override
    public UserVO getUserInfo()
    {
        log.info("开始获取用户信息");
        Long id = BaseContext.getCurrentId();
        if (id == null)
            throw new RuntimeException("用户未登录");
        User user = userMapper.selectById(id);
        return UserVO.builder()
                .id(user.getId())
                .name(user.getName())
                .phone(user.getPhone())
                .idNumber(user.getIdNumber())
                .createTime(user.getCreateTime())
                .seatNumber(user.getSeatNumber())
                .avatar(user.getAvatar())
                .character(user.getCharacter())
                .Is_complete(user.getIsComplete())
                .build();

    };

    @Override
    public void updateUserInfo(UserDTO userDTO) {
        log.info("开始更新用户信息");
        User user = User.builder()
                .id(BaseContext.getCurrentId())
                .phone(userDTO.getPhone())
                .idNumber(userDTO.getIdNumber())
                .build();
        userMapper.updateUserInfo(user);

    }

    @Override
    public List<CharacterVO> getSeatList(){
        log.info("开始获取所有学号");
        List<CharacterVO> seatList = userMapper.getSeatList();
        log.info("获取所有学号成功");
        return seatList;
    };

@Override
    public   void updateCharacter(CharacterDTO character){
    log.info("开始更新用户身份");
    userMapper.updateCharacter(character.getCharacter(),character.getSeatNumber());
};
@Override
    public   void completeUserInfo(Student studentByName)
{
    log.info("开始自动完善用户信息");
    User user = User.builder()
            .id(BaseContext.getCurrentId())
            .name(studentByName.getName())
            .seatNumber(studentByName.getSeatNumber())
            .character(studentByName.getCharacter())
            .IsComplete(1L)
            .build();
            userMapper.updateUserInfo(user);
};

@Override
public User getUserByName(String name)
{
    return userMapper.selectUserByName(name);
}
    private String getOpenID(String code) {
        log.info("开始发送请求，code: {}", code);

        // 检查必要参数
        if (code == null || code.isEmpty()) {
            log.error("微信登录code为空");
            return null;
        }

        if (weChatProperties.getAppid() == null || weChatProperties.getSecret() == null) {
            log.error("微信配置信息不完整，appid: {}, secret: {}",
                    weChatProperties.getAppid(), weChatProperties.getSecret());
            return null;
        }

        Map<String, String> params = new HashMap<>();
        params.put("appid", weChatProperties.getAppid());
        params.put("secret", weChatProperties.getSecret());
        params.put("js_code", code);
        params.put("grant_type", "authorization_code");

        try {
            String json = HttpClientUtil.doGet(WX_LOGIN, params);
            log.info("微信返回结果: {}", json);

            if (json == null || json.isEmpty()) {
                log.error("微信接口返回空结果");
                return null;
            }

            JSONObject jsonObject = JSON.parseObject(json);

            // 检查是否有错误码
            if (jsonObject.containsKey("errcode")) {
                int errcode = jsonObject.getIntValue("errcode");
                String errmsg = jsonObject.getString("errmsg");
                log.error("微信接口调用失败，错误码: {}，错误信息: {}", errcode, errmsg);
                return null;
            }

            String openid = jsonObject.getString("openid");
            if (openid == null || openid.isEmpty()) {
                log.error("微信返回的openid为空");
                return null;
            }

            log.info("成功获取openid: {}", openid);
            return openid;
        } catch (Exception e) {
            log.error("获取openid时发生异常", e);
            return null;
        }
    }





}
